package lbh.crawler;

import java.util.ArrayList;
import java.util.List;

public class ObjectWithLifecycle implements Lifecycle {

	private LifecycleState state = LifecycleState.NEW;

	public ObjectWithLifecycle() {
		super();
	}

	@Override
	public void prepare() {

	}

	@Override
	public void start() {

	}

	@Override
	public void stop() {

	}

	@Override
	public void cleanup() {

	}

	private List<LifecycleListener> listeners = new ArrayList<>();

	@Override
	public void addLifecycleListener(LifecycleListener l) {
		
		synchronized (listeners) {
			listeners.add(l);
		}
	}

	@Override
	public void removeLifecycleListener(LifecycleListener l) {
		
		synchronized (listeners) {
			listeners.remove(l);
		}
	}

	@Override
	public List<LifecycleListener> getLifecycleListeners() {

		return listeners;
	}

	protected void fireLifecycleEvent(String type, Object data) {

		LifecycleEvent event = new LifecycleEvent(this, type, data);
		List<LifecycleListener> interested = new ArrayList<>();	// copy a new list
		interested.addAll(listeners);
		for (LifecycleListener l : interested) {
			l.lifecycleEvent(event);
		}
	}

	public LifecycleState getState() {
		return state;
	}
}